package me.khrystal.rxnews.module.photo.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.socks.library.KLog;

import java.util.List;
import java.util.Random;

import me.khrystal.rxnews.R;
import me.khrystal.rxnews.annotation.ActivityFragmentInject;
import me.khrystal.rxnews.base.BaseFragment;
import me.khrystal.rxnews.base.BaseRecyclerAdapter;
import me.khrystal.rxnews.base.BaseRecyclerViewHolder;
import me.khrystal.rxnews.base.BaseSpacesItemDecoration;
import me.khrystal.rxnews.bean.SinaPhotoList;
import me.khrystal.rxnews.callback.OnItemClickAdapter;
import me.khrystal.rxnews.common.DataLoadType;
import me.khrystal.rxnews.module.photo.presenter.IPhotoListPresenter;
import me.khrystal.rxnews.module.photo.presenter.IPhotoListPresenterImpl;
import me.khrystal.rxnews.module.photo.view.IPhotoListView;
import me.khrystal.rxnews.utils.ClickUtils;
import me.khrystal.rxnews.utils.MeasureUtil;
import me.khrystal.rxnews.widget.AutoLoadMoreRecyclerView;
import me.khrystal.rxnews.widget.ThreePointLoadingView;
import me.khrystal.rxnews.widget.refresh.RefreshLayout;

/**
 * usage:
 * author: kHRYSTAL
 * create time: 16/4/30
 * update time:
 * email: 723526676@qq.com
 */
@ActivityFragmentInject(contentViewId = R.layout.fragment_photo_list)
public class PhotoListFragment extends BaseFragment<IPhotoListPresenter> implements IPhotoListView{

    protected static final String PHOTO_ID = "photo_id";
    protected static final String POSITION = "position";

    protected String mPhotoId;
    protected int mPostion;

    private BaseRecyclerAdapter<SinaPhotoList.DataEntity.PhotoListEntity> mAdapter;
    private AutoLoadMoreRecyclerView mRecyclerView;
    private RefreshLayout mRefreshLayout;

    private ThreePointLoadingView mLoadingView;

    public static PhotoListFragment newInstance(String newsId, int position) {
        PhotoListFragment fragment = new PhotoListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(PHOTO_ID, newsId);
        bundle.putInt(POSITION, position);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments()!=null){
            mPhotoId = getArguments().getString(PHOTO_ID);
            mPostion = getArguments().getInt(POSITION);
        }
    }

    @Override
    protected void initView(View fragmentRootView) {
        mLoadingView = (ThreePointLoadingView)fragmentRootView.findViewById(R.id.tpl_view);
        mLoadingView.setOnClickListener(this);

        mRecyclerView = (AutoLoadMoreRecyclerView)fragmentRootView.findViewById(R.id.recycler_view);
        mRefreshLayout = (RefreshLayout)fragmentRootView.findViewById(R.id.refresh_layout);
//        第一次请求数据 不执行刷新ui的动画
        mPresenter = new IPhotoListPresenterImpl(this,mPhotoId,1);
    }

    @Override
    public void showProgress() {
        mLoadingView.play();
    }

    @Override
    public void hideProgress() {
        mLoadingView.stop();
    }

    @Override
    public void updatePhotoList(List<SinaPhotoList.DataEntity.PhotoListEntity> data, @DataLoadType.DataLoadTypeChecker int type) {
        switch (type){
            case DataLoadType.TYPE_REFRESH_SUCCESS:
                mRefreshLayout.refreshFinish();
                //第一次刷新 需要初始化Adapter
                if (mAdapter == null){
                    initNewsList(data);
                } else {
                    mAdapter.setData(data);
                }
                //之前如果是全部加载完毕的状态（不能再加载）
                //现在重新执行刷新 需要把状态修改为还能够加载更多
                if (mRecyclerView.isAllLoaded()){
                    mRecyclerView.notifyMoreLoaded();
                }
                break;
            case DataLoadType.TYPE_REFRESH_FAIL:
                mRefreshLayout.refreshFinish();
                break;
            case DataLoadType.TYPE_LOAD_MORE_SUCCESS:
                mAdapter.hideFooter();
                if (data==null || data.size()==0){
                    mRecyclerView.isAllLoaded();
                    toast("全部加载完毕噜(☆＿☆)");
                }else {
                    mAdapter.addMoreData(data);
                    mRecyclerView.notifyMoreLoaded();
                }
                break;
            case DataLoadType.TYPE_LOAD_MORE_FAIL:
                mAdapter.hideFooter();
                mRecyclerView.notifyMoreLoaded();
                break;
        }
    }

    private void initNewsList(List<SinaPhotoList.DataEntity.PhotoListEntity> data) {
        final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,
                StaggeredGridLayoutManager.VERTICAL);
        mAdapter = new BaseRecyclerAdapter<SinaPhotoList.DataEntity.PhotoListEntity>(getActivity(),
                data,true,layoutManager) {

            Random mRandom = new Random();

            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.item_photo_summary;
            }

            @Override
            public void bindData(BaseRecyclerViewHolder holder, int position, SinaPhotoList.DataEntity.PhotoListEntity item) {
                final ImageView imageView = holder.getImageView(R.id.iv_photo_summary);
                final ViewGroup.LayoutParams params = imageView.getLayoutParams();
                KLog.e("图片地址:" + item.kpic);
                if (item.picWidth == -1 && item.picHeight == -1){
                    item.picWidth = MeasureUtil.getScreenSize(getActivity()).x / 2 - MeasureUtil
                            .dip2px(getActivity(),4) * 2 - MeasureUtil.dip2px(getActivity(),2);
                    item.picHeight = (int)(item.picWidth * (mRandom.nextFloat() / 2 + 1));
                }
                params.width = item.picWidth;
                params.height = item.picHeight;
                imageView.setLayoutParams(params);

                Glide.with(getActivity()).load(item.kpic).asBitmap()
                        .placeholder(R.drawable.ic_loading).error(R.drawable.ic_fail)
                        .format(DecodeFormat.PREFER_ARGB_8888)
                        .diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);

                holder.getTextView(R.id.tv_photo_summary).setText(item.title);
            }
        };

        mAdapter.setOnItemClickListener(new OnItemClickAdapter() {
            @Override
            public void onItemClick(View view, int position) {

                if (ClickUtils.isFastDoubleClick()){
                    return;
                }

                KLog.e(mAdapter.getData().get(position).title + ";" + mAdapter.getData().get(position).id);

                view = view.findViewById(R.id.iv_photo_summary);
                Intent intent = new Intent(getActivity(),PhotoDetailActivity.class);
                intent.putExtra("photoId",mAdapter.getData().get(position).id);

                ActivityOptionsCompat options = ActivityOptionsCompat
                        .makeScaleUpAnimation(view,view.getWidth() / 2,view.getHeight() /2 ,0,0);
                ActivityCompat.startActivity(getActivity(),intent,options.toBundle());
            }
        });

        mRecyclerView.setAutoLayoutManager(layoutManager).addAutoItemDecoration(
                new BaseSpacesItemDecoration(MeasureUtil.dip2px(getActivity(),4)))
                .setAutoItemAnimator(new DefaultItemAnimator()).setAutoItemAnimatorDuration(250)
                .setAdapter(mAdapter);

        mRecyclerView.setOnLoadMoreListener(new AutoLoadMoreRecyclerView.OnLoadMoreListener() {
            @Override
            public void loadMore() {
                mPresenter.loadMoreData();
                mAdapter.showFooter();
                mRecyclerView.scrollToPosition(mAdapter.getItemCount() - 1);
            }
        });

        mRefreshLayout.setRefreshListener(new RefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                mPresenter.refreshData();
            }
        });
    }
}
